package org.systm.menu.entity;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonValue;

import javax.persistence.AttributeConverter;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MenuType {
    CATALOGUE("catalogue"),
    MENU("menu"),
    PERM("permission");

    @JsonCreator
    public static MenuType fromString(String menuType) {
        for (MenuType item : values()) {
            if (item.getType().equals(menuType.toLowerCase())) {
                return item;
            }
        }
        return null;
    }

    MenuType(String type) {
        this.type = type;
    }

    private final String type;

    @JsonValue
    public String getType() {
        return type;
    }

    public static class Convert implements AttributeConverter<MenuType, String> {
        @Override
        public String convertToDatabaseColumn(MenuType attribute) {
            return attribute.getType().toUpperCase();
        }

        @Override
        public MenuType convertToEntityAttribute(String dbData) {
            MenuType[] values = values();
            for (MenuType menuType : values) {
                if (menuType.getType().equals(dbData.toLowerCase())) {
                    return menuType;
                }
            }
            throw new RuntimeException(String.format("值为%s的枚举类型不存在", dbData));
        }
    }
}
